<?php
declare(strict_types = 1);

namespace App\Model\Logic;

use App\Helper\RedisConst;
use App\Model\Entity\InviteCode;
use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Bean\Annotation\Mapping\Inject;
use Swoft\Redis\Pool;

/**
 * @Bean()
 * Class InviteCodeLogic
 * @package App\Model\Logic
 */
class InviteCodeLogic
{

    /**
     * @Inject()
     * @var Pool
     */
    private $redis;
    /**
     * --------------------------------------------------------------------------
     * 根据用户ID获取邀请码
     * --------------------------------------------------------------------------
     * @param $member_id
     * @return int
     */
    public function getInviteCodeByMemberId($member_id)
    {
        $key = RedisConst::MEMBER_INVITE_CODE . $member_id;
        $code = $this->redis->get($key);
        if($code) return $code;
        //从数据库读取code
        $invite_code = InviteCode::where('member_id', $member_id)->first()->toArray();
        if(!$invite_code){
            $code = $this->bindInvitationCode($member_id);
        } else {
            $code = $invite_code['code'];
        }
        //重新设置缓存
        $this->redis->set($key, $code, RedisConst::NORMAL_EXPIRE);
        return (string) $code;
    }

    /**
     * --------------------------------------------------------------------------
     * 绑定用户邀请码
     * --------------------------------------------------------------------------
     * @param $member_id
     * @return int
     */
    public function bindInvitationCode($member_id)
    {
        $code = $this->createInvitationCode();
        $data = [
            'member_id'  => $member_id,
            'code'       => $code,
            'created_at' => time(),
        ];
        InviteCode::insert($data);
        return $code;
    }

    /**
     * --------------------------------------------------------------------------
     * 邀请码生成
     * --------------------------------------------------------------------------
     * @return int
     */
    public function createInvitationCode()
    {
        while(true){
            $code = rand(111111111, 999999999);
            $exist = $this->redis->sisMember(RedisConst::INVITE_CODE_SET, $code);
            if(!$exist){
                $this->redis->sadd(RedisConst::INVITE_CODE_SET, $code);
                break;
            }
        }
        return $code;
    }

}